using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 吹飞Buff - 将目标吹向指定方���
/// </summary>
public class BlowAwayBuff : BuffBase
{
    private Vector3 m_BlowDirection;
    private float m_BlowForce;
    private float m_BlowDistance;
    private bool m_IsBlownAway;
    private Vector3 m_StartPosition;

    public BlowAwayBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is BlowAwayData blowData)
        {
            m_BlowForce = blowData.BlowForce;
            m_BlowDistance = blowData.BlowDistance;
        }
        else
        {
            m_BlowForce = 12.0f; // 默认吹飞力度
            m_BlowDistance = 8.0f; // 默认吹飞距离
        }
        
        // 计算吹飞方向
        if (Caster != null)
        {
            m_BlowDirection = (Target.transform.position - Caster.transform.position).normalized;
        }
        else
        {
            m_BlowDirection = Vector3.right; // 默认向右吹飞
        }
        
        m_StartPosition = Target.transform.position;
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        m_IsBlownAway = true;
        
        // 播放吹飞特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("blownAway", true);
        }
        
        Logger.Log($"{Target.name} 被吹���");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        if (m_IsBlownAway)
        {
            // 执行吹飞移动
            Vector3 currentPos = Target.transform.position;
            Vector3 newPos = currentPos + m_BlowDirection * m_BlowForce * dt;
            Target.transform.position = newPos;
            
            // 检查是否达到吹飞距���
            float distanceMoved = Vector3.Distance(newPos, m_StartPosition);
            if (distanceMoved >= m_BlowDistance)
            {
                m_IsBlownAway = false;
            }
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        m_IsBlownAway = false;
        Logger.Log($"{Target.name} 吹飞效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        m_IsBlownAway = false;
        
        // 恢复动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("blownAway", false);
        }
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("BlowAway"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 吹飞效果不能叠加，只能刷新持续时���
    }
}
